#include "wingbot_boot.h"

/* 用于测试的函数 */
void test_flash(void)
{
    BootFile_T bf;
    uint32_t i;
    bf.version = 0x00000058;
    bf.totalSize = 0x00001234;

    boot_write_info(BT_DOWNLOAD_START_ADDR, bf);
    
    FLASH_UnlockBank1();
    FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
    
    for(i=0;i<1024;i+=4)
        FLASH_ProgramWord(BT_DOWNLOAD_START_ADDR+8+i, i+8);     //先存入版本信息
    
    FLASH_LockBank1();
    
    boot_transfer_flash(BT_APP_START_ADDR, BT_DOWNLOAD_START_ADDR, 4);
}

int main(void)
{
    __IO BootFileInfo_T* app_info = (__IO BootFileInfo_T*)BT_APP_INFO_ADDR;
    __IO BootFileInfo_T* download_info = (__IO BootFileInfo_T*)BT_DOWNLOAD_INFO_ADDR;
    
    //test_flash();
    
    /* 初次烧录时，BT_DOWNLOAD_INFO_ADDR中的数据全是0xFF，所以会直接跳转到app中运行*/
    /* 上面说的不对，实际测试下来0xFFFFFFFF <= BT_MAX_VERSION为真 */
    if(download_info->version <= BT_MAX_VERSION)
    {
        if(download_info->version > app_info->version)
        {
            if(boot_check_flash_begin(BT_DOWNLOAD_START_ADDR) == WB_NULL)
            {
                /* 如果栈顶地址合法且download区的代码版本更新，则将其拷贝到app区 */
                if(boot_transfer_flash(BT_APP_START_ADDR, BT_DOWNLOAD_START_ADDR, download_info->totalSize) == FLASH_COMPLETE)
                {
                    /* 如果拷贝成功则更新app info信息为最新版本 */
                    BootFile_T bf;
                    bf.version = download_info->version;
                    bf.totalSize = download_info->totalSize;
                    boot_write_info(BT_APP_INFO_ADDR, bf);
                }
            }
        }
    }

    iap_load_app(BT_APP_START_ADDR);
    
    return 0;
}
